<template>
  <div class="app-container">
    <!-- 搜索和操作区域 -->
    <div
      style="
        margin-bottom: 10px;
        display: flex;
        justify-content: space-between;
        align-items: center;
      "
    >
      <div style="display: flex; gap: 10px">
        <!-- 搜索框 -->
        <el-input
          v-model="searchKeyword"
          placeholder="请输入服务器名称或地址"
          clearable
          style="width: 200px"
        />

        <!-- 服务器状态选择框 -->
        <el-select
          v-model="searchStatus"
          placeholder="请选择服务器状态"
          clearable
          style="width: 200px"
        >
          <el-option label="运行中" value="1" />
          <el-option label="已停止" value="2" />
          <el-option label="维护中" value="3" />
        </el-select>

        <!-- 查询按钮 -->
        <el-button type="primary" @click="handleSearch"> 查询 </el-button>
      </div>

      <!-- 新增按钮（调整到最右侧） -->
      <el-button type="primary" @click="handleAdd"> 新增 </el-button>
    </div>

    <!-- 新增账号弹窗 -->
    <el-dialog
      title="新增服务器"
      :visible.sync="addDialogVisible"
      width="400px"
      :close-on-click-modal="false"
    >
      <!-- 新增表单内容保持不变 -->
      <el-form
        :model="addForm"
        :rules="formRules"
        ref="addFormRef"
        label-width="100px"
        class="add-form"
      >
        <!-- 服务器名称输入框 -->
        <el-form-item label="服务器名称" prop="sevName">
          <el-input
            v-model="addForm.sevName"
            placeholder="请输入服务器名称"
            clearable
          />
        </el-form-item>

        <!-- 服务器地址输入框 -->
        <el-form-item label="服务器地址" prop="sevIp">
          <el-input
            v-model="addForm.sevIp"
            placeholder="请输入服务器地址"
            clearable
          />
        </el-form-item>

        <!-- 服务器端口输入框 -->
        <el-form-item label="服务器端口" prop="sevPort">
          <el-input
            v-model.number="addForm.sevPort"
            placeholder="请输入服务器端口"
            clearable
          />
        </el-form-item>

        <!-- 服务器状态选择 -->
        <el-form-item label="服务器状态" prop="sevStatus">
          <el-select
            v-model="addForm.sevStatus"
            placeholder="请选择服务器状态"
            clearable
          >
            <el-option label="运行中" value="1" />
            <el-option label="已停止" value="2" />
            <el-option label="维护中" value="3" />
          </el-select>
        </el-form-item>

        <!-- 备注输入框 -->
        <el-form-item label="备注" prop="sevRemark">
          <el-input
            v-model="addForm.sevRemark"
            placeholder="请输入备注（可选）"
            clearable
            type="textarea"
            rows="3"
          />
        </el-form-item>
      </el-form>

      <!-- 弹窗底部按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="testServerConnection('add')">测试链接</el-button>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAddSubmit">确定新增</el-button>
      </div>
    </el-dialog>

    <!-- 修改弹窗（内容保持不变） -->
    <el-dialog
      title="修改服务器"
      :visible.sync="editDialogVisible"
      width="400px"
      :close-on-click-modal="false"
    >
      <!-- 修改表单内容保持不变 -->
      <el-form
        :model="editForm"
        :rules="formRules"
        ref="editFormRef"
        label-width="100px"
        class="add-form"
      >
        <!-- 服务器名称输入框 -->
        <el-form-item label="服务器名称" prop="sevName">
          <el-input
            v-model="editForm.sevName"
            placeholder="请输入服务器名称"
            clearable
          />
        </el-form-item>

        <!-- 服务器地址输入框 -->
        <el-form-item label="服务器地址" prop="sevIp">
          <el-input
            v-model="editForm.sevIp"
            placeholder="请输入服务器地址"
            clearable
          />
        </el-form-item>

        <!-- 服务器端口输入框 -->
        <el-form-item label="服务器端口" prop="sevPort">
          <el-input
            v-model.number="editForm.sevPort"
            placeholder="请输入服务器端口"
            clearable
          />
        </el-form-item>

        <!-- 服务器状态选择 -->
        <el-form-item label="服务器状态" prop="sevStatus">
          <el-select
            v-model="editForm.sevStatus"
            placeholder="请选择服务器状态"
            clearable
          >
            <el-option label="运行中" value="1" />
            <el-option label="已停止" value="2" />
            <el-option label="维护中" value="3" />
          </el-select>
        </el-form-item>

        <!-- 备注输入框 -->
        <el-form-item label="备注" prop="sevRemark">
          <el-input
            v-model="editForm.sevRemark"
            placeholder="请输入备注（可选）"
            clearable
            type="textarea"
            rows="3"
          />
        </el-form-item>
      </el-form>

      <!-- 弹窗底部按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="testServerConnection('edit')">测试链接</el-button>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEditSubmit">确定修改</el-button>
      </div>
    </el-dialog>

    <!-- 服务器表格（内容保持不变） -->
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="序号" width="95">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>

      <el-table-column
        label="服务器ID"
        width="110"
        align="center"
        :show-overflow-tooltip="true"
        v-if="false"
      >
        <template slot-scope="scope">
          {{ scope.row.sev_id }}
        </template>
      </el-table-column>

      <el-table-column label="服务器名称" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.sev_name }}</span>
        </template>
      </el-table-column>

      <el-table-column label="服务器地址" width="210" align="center">
        <template slot-scope="scope">
          {{ scope.row.sev_ip }}
        </template>
      </el-table-column>

      <el-table-column label="服务器端口" width="110" align="center">
        <template slot-scope="scope">
          {{ scope.row.sev_port }}
        </template>
      </el-table-column>

      <el-table-column label="服务器状态" width="110" align="center">
        <template slot-scope="scope">
          {{ formatRole(scope.row.sev_status) }}
        </template>
      </el-table-column>

      <el-table-column label="备注" width="500" align="center">
        <template slot-scope="scope">
          {{ scope.row.sev_remark }}
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        prop="created_at"
        label="添加时间"
        width="200"
      >
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span>{{ scope.row.add_time }}</span>
        </template>
      </el-table-column>

      <el-table-column
        class-name="operation-col"
        label="操作"
        width="200"
        align="center"
      >
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handleEdit(scope.row)">
            修改
          </el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)"
            style="margin-left: 5px"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin-top: 10px; text-align: right">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import {
  getList,
  addServer,
  testConnection,
  delServer,
  updateServer,
} from "@/api/servertable";

export default {
  data() {
    const validateIpv4 = (rule, value, callback) => {
      const ipv4Regex =
        /^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
      if (!value) {
        callback(new Error("请输入服务器地址"));
      } else if (!ipv4Regex.test(value)) {
        callback(new Error("请输入有效的IPv4地址"));
      } else {
        callback();
      }
    };

    return {
      list: null,
      listLoading: true,
      // 新增搜索相关数据
      searchKeyword: "", // 搜索关键词
      searchStatus: "", // 搜索状态

      // 新增弹窗控制
      addDialogVisible: false,
      // 新增表单数据
      addForm: {
        sevName: "",
        sevIp: "",
        sevPort: "",
        sevStatus: "",
        sevRemark: "",
      },
      // 修改弹窗控制
      editDialogVisible: false,
      // 修改表单数据
      editForm: {
        sevId: "",
        sevName: "",
        sevIp: "",
        sevPort: "",
        sevStatus: "",
        sevRemark: "",
      },
      // 表单验证规则
      formRules: {
        sevName: [
          { required: true, message: "请输入服务器名称", trigger: "blur" },
        ],
        sevIp: [
          { required: true, message: "请输入服务器地址", trigger: "blur" },
          { validator: validateIpv4, trigger: "blur" },
        ],
        sevPort: [
          { required: true, message: "请输入服务器端口", trigger: "blur" },
          {
            type: "number",
            message: "端口必须是数字",
            trigger: "blur",
          },
          {
            validator: (rule, value, callback) => {
              const port = Number(value);
              if (isNaN(port)) {
                callback(new Error("端口必须是数字"));
              } else if (port < 1 || port > 65535) {
                callback(new Error("端口范围必须在1-65535之间"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        sevStatus: [
          { required: true, message: "请选择服务器状态", trigger: "change" },
        ],
      },
      // 分页相关数据
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页显示条数
      totalCount: 0, // 总记录数
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    // 获取表格数据
    fetchData() {
      this.listLoading = true;
      const params = {
        page: this.currentPage,
        limit: this.pageSize,
        keyword: this.searchKeyword,
        status: this.searchStatus,
      };

      getList()
        .then((response) => {
          console.log(response.data);
          this.list = response.data.list;
          this.totalCount = response.data.total;
          this.listLoading = false;
        })
        .catch(() => {
          this.listLoading = false;
          this.$message.error("数据加载失败，请重试");
        });
    },

    // 新增查询方法
    handleSearch() {
      // 这里可以根据实际需求实现查询逻辑
      // 示例：调用后端接口时传入搜索参数
      this.listLoading = true;
      // 假设getList方法支持传入查询参数
      getList({
        keyword: this.searchKeyword,
        status: this.searchStatus,
      })
        .then((response) => {
          this.list = response.data.list;
          this.totalCount = response.data.total;
          this.listLoading = false;
        })
        .catch(() => {
          this.listLoading = false;
          this.$message.error("查询失败，请重试");
        });
      this.currentPage = 1;
    },

    // 每页条数改变时触发
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1; // 重置到第一页
      this.fetchData();
    },

    // 当前页码改变时触发
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchData();
    },

    formatRole(roleValue) {
      const roleMap = {
        1: "运行中",
        2: "已停止",
        3: "维护中",
      };
      return roleMap[roleValue] || "未知角色";
    },

    // 打开新增弹窗
    handleAdd() {
      this.$nextTick(() => {
        this.$refs.addFormRef.resetFields();
      });
      this.addDialogVisible = true;
    },

    // 提交新增表单
    handleAddSubmit() {
      this.$refs.addFormRef.validate((isValid) => {
        if (isValid) {
          const addParams = {
            sev_name: this.addForm.sevName,
            sev_ip: this.addForm.sevIp,
            sev_port: this.addForm.sevPort,
            sev_status: this.addForm.sevStatus,
            sev_remark: this.addForm.sevRemark,
          };

          addServer(addParams)
            .then(() => {
              this.$message.success("服务器新增成功");
              this.addDialogVisible = false;
              this.fetchData();
            })
            .catch(() => {
              this.$message.error("服务器新增失败，请重试");
            });
        } else {
          return false;
        }
      });
    },

    testServerConnection(formType) {
      const formRef = formType === "add" ? "addFormRef" : "editFormRef";
      const formData = formType === "add" ? this.addForm : this.editForm;

      this.$refs[formRef].validate(
        (valid) => {
          if (valid) {
            this.$message.info(
              `正在测试连接: ${formData.sevIp}:${formData.sevPort}`
            );

            testConnection({
              ip: formData.sevIp,
              port: formData.sevPort,
            })
              .then(() => {
                this.$message.success("连接测试成功");
              })
              .catch(() => {
                this.$message.error("连接测试失败");
              });
          }
        },
        ["sevIp", "sevPort"]
      );
    },

    // 打开修改弹窗
    handleEdit(row) {
      this.$nextTick(() => {
        this.$refs.editFormRef.resetFields();
      });
      this.editForm = {
        sevId: row.sev_id,
        sevName: row.sev_name,
        sevIp: row.sev_ip,
        sevPort: row.sev_port,
        sevStatus: row.sev_status,
        sevRemark: row.sev_remark || "",
      };
      this.editDialogVisible = true;
    },

    // 提交修改表单
    handleEditSubmit() {
      this.$refs.editFormRef.validate((isValid) => {
        if (isValid) {
          const editParams = {
            sev_id: this.editForm.sevId,
            sev_name: this.editForm.sevName,
            sev_ip: this.editForm.sevIp,
            sev_port: this.editForm.sevPort,
            sev_status: this.editForm.sevStatus,
            sev_remark: this.editForm.sevRemark,
          };

          updateServer(editParams)
            .then(() => {
              this.$message.success("服务器修改成功");
              this.editDialogVisible = false;
              this.fetchData();
            })
            .catch(() => {
              this.$message.error("服务器修改失败，请重试");
            });
        } else {
          return false;
        }
      });
    },

    // 删除操作
    handleDelete(row) {
      this.$confirm("确定要删除该资源吗？", "删除确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delServer(row.sev_id)
            .then(() => {
              this.$message.success("资源删除成功");
              this.fetchData();
            })
            .catch(() => {
              this.$message.error("删除失败");
            });
        })
        .catch(() => {
          this.$message({ type: "info", message: "已取消删除" });
        });
    },
  },
};
</script>

<style scoped>
.add-form {
  margin-top: 15px;
}
.dialog-footer {
  text-align: right;
}
</style>
